/**
 * SysResourceAction.java
 * Created at 2016-5-5
 * Created by Tangsanlin
 * Copyright (C) 2016 BROADTEXT SOFTWARE, All rights reserved.
 */
package com.broadtext.rms.system.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.broadtext.common.bean.EntityPageBean;
import com.broadtext.common.exp.DaoException;
import com.broadtext.common.exp.ServiceException;
import com.broadtext.common.utils.RmsUtil;
import com.broadtext.common.utils.UUIDUtils;
import com.broadtext.rms.system.model.SysResource;
import com.broadtext.rms.system.service.ISysDictIndexService;
import com.broadtext.rms.system.service.ISysResourceService;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;

@Controller
@RequestMapping("/main/sysResource")
public class SysResourceAction {
	/**
     * sysResourceService 
     */
    @Autowired
    @Qualifier("sysResourceService")
    private ISysResourceService sysResourceService;
    
    /**
     * 字典service
     */
    @Autowired
    @Qualifier("sysDictIndexService")
    private ISysDictIndexService sysDictIndexService;

    /**
     * <p>
     * Description: 查询资源信息
     * </p>
     * 
     * @param request 请求对象
     * @param response 返回对象
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "/getResource.mvc")
    @ResponseBody
    public void getResource(HttpServletRequest request, HttpServletResponse response) {
        try {
            PageBounds pageBounds;
            pageBounds = new PageBounds();
            Map<String, Object> map;
            String aoData;
            aoData = request.getParameter("aoData");
            JSONArray array;
            array = JSON.parseArray(aoData);
            map = new HashMap<String, Object>();
            if (array != null) {
                Iterator it;
                it = array.iterator();
                while (it.hasNext()) {
                    JSONObject obj;
                    obj = (JSONObject) it.next();
                    if(obj.get("value")!=null && !"".equals(obj.get("value")+"")){
                        map.put(obj.get("name")+"", obj.get("value"));
                    }
                }
            }
            pageBounds.setLimit(Integer.parseInt(map.get("iDisplayLength").toString()));
            pageBounds.setPage(Integer.parseInt(map.get("iDisplayStart").toString()) / pageBounds.getLimit()+1);
            EntityPageBean<SysResource> pageBean = this.sysResourceService.findEntityPageByQuery(map, pageBounds);
            Map dataMap=new HashMap();
            dataMap.put("recordsTotal", pageBean.getiTotalRecords());
            dataMap.put("recordsFiltered", pageBean.getiTotalRecords());
            dataMap.put("aaData", pageBean.getResults());
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = null;
            try {
                out = response.getWriter();
                out.write(JSON.toJSONString(dataMap));
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (out != null) {
                    out.close();
                }
            }
        } catch (ServiceException e) {
            e.printStackTrace();
        }

    }
    /**
     * <p>
     * Description: 获取资源树形结构
     * </p>
     * @param request 请求对象
     * @param response 返回对象
     * @return map数据
     */
    @RequestMapping(value = "/getResourceTree.mvc")
    @ResponseBody
    public Map<String, Object> getResourceTree(HttpServletRequest request, HttpServletResponse response) {
	    Map<String, Object> dataMap;
	    dataMap = new HashMap<String, Object>();
	    List<SysResource> list;
	    list = new ArrayList<SysResource>();
	    String type = request.getParameter("id");
	    try {
	        list = this.sysResourceService.getResourceTree(type);
	    } catch (DaoException e) {
	        e.printStackTrace();
	    }
	    dataMap.put("aaData", list);
	    return dataMap;
    }
    
    /**
     * 
     * <p>Description: 初始化编辑页面</p>
     * @param id 编辑对象id
     * @param request 请求对象
     * @param response 返回对象
     * @throws ServiceException 异常
     * @throws DaoException 异常
     */
    @RequestMapping(value = "/initEditResourceById")
    @ResponseBody
    public void initEditResourceById(String id, HttpServletRequest request, HttpServletResponse response) throws ServiceException, DaoException {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("resource", this.sysResourceService.findEntityById(id));
        map.put("resTypeDict", this.sysDictIndexService.getDictByParentKey("SYS_ZYLBDM"));
        map.put("resTree", this.sysResourceService.getResourceTree(null));
        RmsUtil.writeJsonStr(response, JSON.toJSONString(map));
    }
    
    /**
     * <p>Description: 保存 或 更新资源</p>
     * @param request 请求
     * @param response 响应
     * @return String 操作结果
     */
    @RequestMapping(value = "/saveOrUpdateSysResource.mvc")
    @ResponseBody
    public Map<String, Object> saveOrUpdateSysResource(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> dataMap;
        dataMap = new HashMap<String, Object>();
        dataMap.put("mes", "success");
        try {
            String record;
            record = request.getParameter("record");
            JSONObject jsonOb;
            jsonOb = JSON.parseObject(record);
            SysResource resource;
            resource = new SysResource();
            if (jsonOb.get("id") != null && !"".equals(jsonOb.get("id"))) {
                resource = this.sysResourceService.findEntityById(String.valueOf(jsonOb.get("id")));
                if (resource == null) {
                    dataMap.put("msg", "error");
                    return dataMap;
                }
            }
            if (jsonOb.get("resName") != null && !"".equals(jsonOb.get("resName"))) {
                resource.setResName(String.valueOf(jsonOb.get("resName")));
            }
            if (jsonOb.get("resUrl") != null && !"".equals(jsonOb.get("resUrl"))) {
                resource.setResUrl(String.valueOf(jsonOb.get("resUrl")));
            }
            if (jsonOb.get("parentId") != null && !"".equals(jsonOb.get("parentId"))) {
                resource.setParentId(String.valueOf(jsonOb.get("parentId")));
            }
            if (jsonOb.get("resSort") != null && !"".equals(jsonOb.get("resSort"))) {
                resource.setResSort(String.valueOf(jsonOb.get("resSort")));
            }
            if (jsonOb.get("resType") != null && !"".equals(jsonOb.get("resType"))) {
                resource.setResType(String.valueOf(jsonOb.get("resType")));
            }
            if (jsonOb.get("remark") != null && !"".equals(jsonOb.get("remark"))) {
                resource.setRemark(String.valueOf(jsonOb.get("remark")));
            }
            resource.setUpdateDate(new Date());
            resource.setUpdateUser(String.valueOf(request.getSession().getAttribute("sys.userName")));
            if (resource.getPkId() != null) {
                dataMap.put("msg", this.sysResourceService.updateSysResource(resource));
            } else {
            	resource.setPkId(UUIDUtils.getUUID());
                resource.setDelFlag("0");
                resource.setCreateDate(new Date());
                resource.setCreateUser(String.valueOf(request.getSession().getAttribute("sys.userName")));
                dataMap.put("msg", this.sysResourceService.insertSysResource(resource));
            }
        } catch (ServiceException e) {
            e.printStackTrace();
        } catch (DaoException e) {
            e.printStackTrace();
        }
        return dataMap;

    }
    
    /**
     * <p>
     * Description: 删除目录
     * </p>
     * 
     * 
     * @param request 请求
     * @param pkId 资源id
     * @param response 返回对象
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    @RequestMapping(value = "/delResource.mvc")
    @ResponseBody
    public void delResource(HttpServletRequest request, String pkId, HttpServletResponse response) {
        String[] resIdArray;
        resIdArray = pkId.split(",");
        try {
            this.sysResourceService.delSysResource(resIdArray,
                    String.valueOf(request.getSession().getAttribute("sys.userName")));
        } catch (DaoException e) {
            e.printStackTrace();
        }
        Map dataMap;
        dataMap = new HashMap();
        dataMap.put("msg", "SUCCESS");
        RmsUtil.writeJsonStr(response, JSON.toJSONString(dataMap));
    }
}
